<template>
  <div class="crowdfunding-page">
    <!-- 众筹项目列表 -->
    <el-card v-for="item in projectList" :key="item.id" class="project-card">
      <!-- 项目基本信息 -->
      <div class="project-header">
        <div class="project-info">
          <el-image :src="item.image" class="project-image" />
          <div class="project-detail">
            <h3>{{ item.projectName }}</h3>
            <el-tag 
              size="small" 
              :type="getStatusType(item.projectStatus)"
            >
              {{ getStatusText(item.projectStatus) }}
            </el-tag>
          </div>
        </div>
        <div class="order-info">
          <p>订单号：{{ item.orderNum }}</p>
          <p>下单时间：{{ item.createTime }}</p>
        </div>
      </div>

      <!-- 众筹进度 -->
      <div class="progress-section">
        <el-progress 
          :percentage="((item.currentQuantity / item.targetQuantity) * 100).toFixed(2)"
          :status="item.status === 'failed' ? 'exception' : ''"
        />
        <div class="progress-info">
          <div class="info-item">
            <span class="label">目标数量</span>
            <span class="value">{{ item.targetQuantity }}件</span>
          </div>
          <div class="info-item">
            <span class="label">已筹数量</span>
            <span class="value">{{ item.currentQuantity }}件</span>
          </div>
          <div class="info-item">
            <span class="label">我的认购</span>
            <span class="value highlight">{{ item.quantity }}件</span>
          </div>
          <div class="info-item">
            <span class="label">剩余时间</span>
            <span class="value">{{ item.remainingDays }}天</span>
          </div>
        </div>
      </div>

      <!-- 规格信息 -->
      <div class="specs-section">
        <div class="specs-title">已选规格：</div>
        <div class="specs-list">
          <span class="spec-item">颜色：{{ item.color }} 尺寸：{{ item.size }}</span>
        </div>
      </div>

      <!-- 底部操作区 -->
      <div class="card-footer">
        <div class="price-info">
          <div class="price">众筹价：¥{{ item.price }}</div>
          <div class="total">总金额：¥{{ item.price * item.quantity }}</div>
        </div>
        <div class="actions">
          <el-button 
            v-if="item.projectStatus === 'funding'"
            type="danger" 
            @click="handleQuit(item)"
          >
            退出众筹
          </el-button>
          <el-button 
            type="primary"
            @click="viewDetail(item.projectId)"
          >
            查看详情
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 空状态 -->
    <el-empty
      v-if="projectList.length === 0"
      description="暂无参与的众筹项目"
    />

    <!-- 退出确认弹窗 -->
    <el-dialog
      v-model="quitDialogVisible"
      title="退出众筹"
      width="400px"
    >
      <div class="quit-dialog">
        <p>确定要退出该众筹项目吗？</p>
        <div class="quit-info">
          <p>退款金额：<span class="amount">¥{{ currentItem.price * currentItem.quantity }}</span></p>
          <p class="tip">退款将在3-5个工作日内退回支付账户</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="quitDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmQuit">确认退出</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getUserCrowdFundingListAPI, quitCrowdFundingAPI } from '@/api/store'
import { useTokenStore } from '@/store/token'

// 获取登录用户信息
const tokenStore = useTokenStore();
const userId = tokenStore.user.userId;


const router = useRouter()
const quitDialogVisible = ref(false)
const currentItem = ref(null)

// 模拟数据
// const projectList = ref([
//   {
//     id: 1,
//     image: 'https://example.com/image.jpg',
//     title: '2024春季班服定制',
//     status: 'funding',
//     orderNo: 'CF20240301001',
//     createTime: '2024-03-01 14:30',
//     targetQuantity: 100,
//     currentQuantity: 68,
//     myQuantity: 2,
//     remainingDays: 15,
//     price: 99,
//     amount: 198,
//     specs: [
//       { id: 1, color: '白色', size: 'M', quantity: 1 },
//       { id: 2, color: '黑色', size: 'L', quantity: 1 }
//     ]
//   },
//     {
//     id: 1,
//     image: 'https://example.com/image.jpg',
//     title: '2024春季班服定制',
//     status: 'success',
//     orderNo: 'CF20240301001',
//     createTime: '2024-03-01 14:30',
//     targetQuantity: 100,
//     currentQuantity: 100,
//     myQuantity: 2,
//     remainingDays: 15,
//     price: 99,
//     amount: 198,
//     specs: [
//       { id: 1, color: '白色', size: 'M', quantity: 1 },
//       { id: 2, color: '黑色', size: 'L', quantity: 1 }
//     ]
//   }
// ])

const projectList = ref({})

const getCrowdFundingList = async () => {
  // 调用接口获取用户众筹列表
  const res = await getUserCrowdFundingListAPI(userId)
  const projectListData = res.data;
  // 遍历项目列表，计算每个项目的剩余天数
  const projectListWithRemainingDays = projectListData.map(project => {
    const now = new Date();
    const endTime = new Date(project.endTime);
    const diffTime = endTime - now;
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return {
      ...project,
      remainingDays: diffDays >= 0 ? diffDays : 0 // 如果已经过期，返回0
    };
  });

  // 更新项目列表
  projectList.value = projectListWithRemainingDays;
  console.log(projectList.value);
}

// 状态处理
const getStatusType = (status) => {
  const typeMap = {
    funding: 'warning',    // 募集中
    success: 'success',    // 募集成功
    failed: 'danger',      // 募集失败
    completed: 'info'       // 配送中
  }
  return typeMap[status]
}

const getStatusText = (status) => {
  const textMap = {
    funding: '募集中',
    success: '已达成',
    failed: '未达成',
    completed: '已完成'
  }
  return textMap[status]
}

// 查看详情
const viewDetail = (id) => {
const routeData = router.resolve({
    name: 'crowdFundingDetail',
    params: { projectid: id }
  })
  // 在新窗口打开
  window.open(routeData.href, '_blank')
}

// 退出众筹
const handleQuit = (item) => {
  currentItem.value = item
  quitDialogVisible.value = true
}

// 确认退出
const confirmQuit = async () => {
  try {
    //调用退出接口
    await quitCrowdFundingAPI({ userId: currentItem.value.userId,projectId: currentItem.value.projectId })
    ElMessage.success('退出成功')
    quitDialogVisible.value = false
    // 刷新列表
    getCrowdFundingList()
  } catch (error) {
    ElMessage.error('退出失败')
  }
}

onMounted(() => {
  getCrowdFundingList()
})
</script>

<style scoped lang="scss">
.crowdfunding-page {
  padding: 20px;

  .project-card {
    margin-bottom: 20px;

    .project-header {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20px;

      .project-info {
        display: flex;
        align-items: flex-start;

        .project-image {
          width: 100px;
          height: 100px;
          margin-right: 15px;
          border-radius: 4px;
        }

        .project-detail {
          h3 {
            margin: 0 0 10px 0;
          }
        }
      }

      .order-info {
        text-align: right;
        color: #666;
        font-size: 14px;

        p {
          margin: 5px 0;
        }
      }
    }

    .progress-section {
      margin: 20px 0;

      .progress-info {
        display: flex;
        justify-content: space-around;
        margin-top: 15px;
        text-align: center;

        .info-item {
          .label {
            display: block;
            color: #666;
            font-size: 12px;
            margin-bottom: 5px;
          }

          .value {
            font-size: 16px;
            font-weight: bold;

            &.highlight {
              color: #409EFF;
            }
          }
        }
      }
    }

    .specs-section {
      margin: 15px 0;
      padding: 15px 0;
      border-top: 1px solid #eee;
      font-size: 14px;

      .specs-title {
        color: #666;
        margin-bottom: 10px;
      }

      .spec-item {
        margin-right: 15px;
        color: #666;
      }
    }

    .card-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-top: 15px;
      border-top: 1px solid #eee;

      .price-info {
        .price {
          margin-bottom: 5px;
        }
        .total {
          color: #ff4400;
          font-weight: bold;
        }
      }

      .actions {
        .el-button + .el-button {
          margin-left: 10px;
        }
      }
    }
  }
}

.quit-dialog {
  text-align: center;

  .quit-info {
    margin-top: 20px;
    padding: 15px;
    background: #f8f8f8;
    border-radius: 4px;

    .amount {
      color: #ff4400;
      font-size: 18px;
      font-weight: bold;
    }

    .tip {
      color: #999;
      font-size: 12px;
      margin-top: 10px;
    }
  }
}
</style>